package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单定时任务
 */
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单超时处理
     *   如果一个订单超过15分钟还没有支付,则改为 已取消状态
     */
   // @Scheduled(cron = "0 * * * * *")
//    @Scheduled(cron = "0/10 * * * * *")
    public void timeOutOrder(){
      //1 查询所有 15 分钟前 未支付的订单
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList =  orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,dateTime);
        //2 更新状态
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);// 已取消
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("支付超时");
            orderMapper.update(orders);
        }
    }
    /**
     * 订单送达状态修改
     *   如果一个订单第二天凌晨1点还没有 送达,则自动更新成已完成
     */
    @Scheduled(cron = "0 0 1 * * *")
    //@Scheduled(cron = "0/10 * * * * *")
    public void deliveryOrder(){
        //1 查询所有 60分钟前 未送达的数据
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-60);

        List<Orders> ordersList =  orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,dateTime); // 配送中
        //2 更新状态
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.COMPLETED);// 已完成
            orderMapper.update(orders);
        }
    }

}
